import { ImageSpec } from "../consts/Assets";

export default class ScreenManager {
    public static screenshot: Image;
    public static lastScreenshotTime: number;

    public static captureScreen(): void {
        this.lastScreenshotTime = new Date().getTime();
        this.screenshot = images.captureScreen();
    }

    /**
     * 判断某个区域是否是指定图片
     * @param screenshot 
     * @param imgSpec 
     */
    public static matchImage(imgSpec: ImageSpec): boolean {
        if (imgSpec.alpha) {
            return this.matchImageEx(imgSpec);
        }

        let points: any[] = images.matchTemplate(this.screenshot, imgSpec.img, {
            threshold: 0.4,
            region: imgSpec.region
        }).points;

        return points.length > 0;
    }

    /**
     * 判断某个区域是否是指定图片，带透明区域
     * @param screenshot 
     * @param imgSpec 
     */
    public static matchImageEx(imgSpec: ImageSpec): boolean {
        let isMatch: boolean = images.matchTemplateEx(this.screenshot, imgSpec.img, {
            region: imgSpec.region,
            threshold: 0.4,
        });

        return isMatch;
    }

    /**
     * 等待某张图片出现
     * @param screenshot 
     * @param imgSpec 
     */
    public static waitImage(imgSpec: ImageSpec): void {
        do {
            sleep(1000);
            this.screenshot = images.captureScreen();
            if (this.matchImage(imgSpec)) {
                break;
            }
        } while (1);
    }

    public static recognizeImage(ic: any, ...r: number[]): string {
        let clip = images.clip(this.screenshot, r[0], r[1], r[2], r[3]);
        let bestClass = ic.recognizeImage(clip);
        clip.recycle();
        return bestClass;
    }
}